# coding=utf8
import json

import falcon
from bson import ObjectId

from libs.help import stream_to_params
from models.user.ad import model_user_ad
from models.user.info import model_user_info
from models.user.wx import model_user_wx


class WxResource:
    def on_options(self, req, resp):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_get(self, req, resp):
        uid = req.get_header('uid')

        userinfo = model_user_info.coll.find_one({'_id': ObjectId(uid)}, {'PassWd': 0})
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        if userinfo is None:
            resp.body = json.dumps({
                'info': {
                    'code': 500,
                    'codeMessage': '呵呵呵'
                }
            })
        else:
            accounts = userinfo['WxAccounts']
            for account in accounts:
                account['left_num'] = model_user_wx.get_left(account['appid'])
                # 根据appid去获取广告
                ad = model_user_ad.coll.find_one({'appid': account['appid']})
                if ad is None:
                    account['ad_title'] = ''
                else:
                    account.update({
                        'ad_title': ad['AdTitle'],
                        'ad_id': str(ad['AdId'])
                    })

            resp.body = json.dumps({
                'info': {
                    'code': 200
                },
                'item': {
                    'uid': str(userinfo['_id']),
                    'username': userinfo['UserName'],
                    'wx_accounts': accounts
                }
            })

    def on_post(self, req, resp):
        data = req.stream.read().decode()
        data = stream_to_params(data)

        uid = req.get_header('uid')

        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')

        if model_user_info.coll.find_one({
            'WxAccounts': {
                '$elemMatch': {
                    'appid': data['appid']
                }
            }
        }) is not None:
            resp.body = json.dumps({
                'info': {
                    'code': 500,
                    'codeMessage': 'appid已经存在'
                }
            })
        else:
            model_user_info.coll.update({'_id': ObjectId(uid)}, {
                '$push': {
                    'WxAccounts': {
                        'appid': data['appid'],
                        'appsecret': data['appsecret'],
                        'remark': data['remark']
                    }
                }
            })
            resp.body = json.dumps({
                'info': {
                    'code': 200
                }
            })


class WxAccountResource:
    def on_options(self, req, resp, n):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_post(self, req, resp, n):
        uid = req.get_header('uid')

        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')
        resp.set_header('Access-Control-Allow-Headers', 'uid')

        data = model_user_info.coll.find_one({'_id': ObjectId(uid)})['WxAccounts'][int(n)]
        # 删除那个啥
        model_user_wx.delete(data['appid'])

        model_user_info.coll.update({'_id': ObjectId(uid)}, {
            '$pop': {
                'WxAccounts': int(n)
            }
        })

        resp.body = json.dumps({
            'info': {
                'code': 200
            }
        })
